package com.dhecp.project.bi.controller;

import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.layui.TreeDataModel;
import com.dhecp.core.layui.TreeDataUtil;
import com.dhecp.project.base.domain.BaseInfo;
import com.dhecp.project.base.service.BaseInfoService;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bi/bistockon")
public class BiStockOnController extends BaseController {

    private String prefix = "bi/bistockon";

    @Autowired
    private BaseInfoService baseInfoService;

    @Autowired
    private TreeDataUtil treeDataUtil;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;


    
    /**
     * 打开基础数据列表
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:view")
    @GetMapping()
    public ModelAndView baseinfo(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        System.out.println(prefix);
        mv.setViewName(prefix + "/bistockon");
        return mv;
    }

    /**
     * 打开基础数据新增页
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:base:add")
    @GetMapping("/add")
    public ModelAndView baseInfoAdd(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "moduleTable","基础数据表标识");
        }
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "vtype","基础数据分项");
        }
        if (mv.isEmpty()){
        	String pguid = "";
        	String pvname = "";
        	if (params.get("pguid") != null && params.get("pguid") != ""){
        		pguid = params.get("pguid").toString();
        	}
        	if (params.get("pvname") != null && params.get("pvname") != ""){
        		pvname = params.get("pvname").toString();
        	}
        	params.put("entity", new BaseInfo());
            AjaxResult ajaxResult = new AjaxResult();
    		List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
    		List<Map<String, Object>> fieldsListTemp = new ArrayList<Map<String, Object>>(); //临时存储区，用于存放需要放到最后生成的控件，如：备注等大文本控件
            List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
            List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        	try{
            	params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
        		dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
                if (dicFieldsList.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                    ajaxResult = AjaxResult.success("数据获取成功。");
                    BaseInfo baseInfo = new BaseInfo();
                    baseInfo.setBdefault(false);
                    baseInfo.setBdeleted(false);
                    baseInfo.setFvalue(0.0);
                    baseInfo.setIid(0);
                    baseInfo.setPguid(pguid);
                    baseInfo.setPguidName(pvname);
                    baseInfo.setvAccount("");
                    baseInfo.setvAccountName("");
                    baseInfo.setvCID("");
                    baseInfo.setVid("");
                    baseInfo.setVname("");
                    baseInfo.setVremark("");
                    baseInfo.setVtype(params.get("vtype").toString());
                	for (SysDictionaryForPageField dicFields : dicFieldsList){
                		Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                		Map<String, Object> baseInfoMap = TypeUtils.entityToMap(baseInfo);
                		fieldsListMap.put("fieldContent", baseInfoMap.get(fieldsListMap.get("fields")));
                		
                		if (fieldsListMap.get("fieldFrontType") == null){
                			fieldsListMap.put("fieldFrontType", "t_text");
                		}
                		
                		if ("t_textarea".equals(fieldsListMap.get("fieldFrontType").toString())){ //大文本控件放入临时存储区
                			fieldsListTemp.add(fieldsListMap);
                		}else if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                			fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                		}else if ((Integer)fieldsListMap.get("fieldFrontTop") == 2){	//隐藏的字段
                			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                		}
                	}
                	if (!fieldsListTemp.isEmpty() && fieldsListTemp.size() > 0){
                		for (Map<String, Object> fieldsMap : fieldsListTemp){ 			//大文本控件追加到数组末尾
                			if ((Integer)fieldsMap.get("fieldFrontTop") == 1){			//显示的字段
                    			fieldsList.add(TypeUtils.mapToJson(fieldsMap));
                    		}else if ((Integer)fieldsMap.get("fieldFrontTop") == 2){	//隐藏的字段
                    			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsMap));
                    		}
                		}
                	}
                }
                mv.addObject("fieldsList", fieldsList);				//显示的字段
                mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
                mv.addObject("vtype", params.get("vtype"));
        	}catch(Exception e){
        		ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        	}
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/baseinfo_add");
        }
        return mv;
    }


    /**
     * 通过传入的条件查询基础数据列表
     * @param params
     * @return GridDataModel
     * @throws Exception
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:base:list")
    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) throws Exception{
        List<BaseInfo> list = new ArrayList<BaseInfo>();
        try {
        	if (params.get("vtype") == null || params.get("vtype") == ""){
        		params.put("moduleTable", "TB_baseinfo");
        	}else{
                String vtype = params.get("vtype").toString();
                String moduleTable = "TB_baseinfo_" + vtype;
                moduleTable = (moduleTable.toLowerCase().indexOf("tb_baseinfo_area") == -1 ? moduleTable : "tb_baseinfo_area");
        		params.put("moduleTable", moduleTable);
        	}
            list = baseInfoService.queryBaseInfoList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());   
        }
        return getDataTable(list);
    }

    /**
     * 通过传入的条件查询基础数据树
     * @param params
     * @return TreeDataModel
     * @throws Exception
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:base:list")
    @RequestMapping("/listtreejson")
    @ResponseBody
    public Object baseInfoTreeJson(@RequestParam Map<String, Object> params) throws Exception{
        if (params.get("rootvtype") == null || params.get("rootvtype") == ""){
            //根节点类型，若未传入默认为区域"area"
            params.put("rootvtype", "area1");
        }
        List<TreeDataModel> treeDataModelList = new ArrayList<TreeDataModel>();
        try{
            treeDataModelList = baseInfoService.queryBaseInfoTree(params);
            treeDataModelList = treeDataUtil.dealTreeDataModel(treeDataModelList,treeDataModelList.get(0).getMaxlevels());
        }catch(Exception e){
            return treeDataModelList;
        }
        return treeDataModelList;
    }

}
